package com.faiz.algorithm;

import java.util.HashMap;
import java.util.Map;

public class MinWindow2 {
    public String minWindow(String s, String t) {
        if (s.length() < t.length()) return "";

        // 思路：先找到一个包含的字符串，然后再来优化使其变短
        Map<Character, Integer> need = new HashMap<>();
        Map<Character, Integer> window = new HashMap<>();

        // 初始化条件
        for (char c : t.toCharArray())
            addOrRemove(need, c, true);

        int min = Integer.MAX_VALUE;
        String res = "";

        int left = 0, right = 0;
        // 满足的校验项数量
        int valid = 0;
        while (right < s.length()) {
            // 加入到窗口中
            char c = s.charAt(right);
            addOrRemove(window, c, true);
            // 增加校验项
            if (window.get(c).equals(need.getOrDefault(c, 0))) valid++;
            // 开始缩小窗口
            while (valid == need.size()) {
                char d = s.charAt(left);
                // 此时处于临界状态
                if (window.get(d).equals(need.getOrDefault(d, 0))) {
                    valid--;
                    // 一定要在此处更新结果，因为此时的结果才是最小的
                    int cur = right - left + 1;
                    if (min > cur) {
                        min = cur;
                        res = s.substring(left, right + 1);
                    }
                }
                addOrRemove(window, d, false);
                left++;
            }
            right++;
        }
        return res;
    }

    private void addOrRemove(Map<Character, Integer> map, char c, boolean isAdd) {
        map.computeIfAbsent(c, k -> 0);

        if (isAdd) {
            map.computeIfPresent(c, (k, v) -> v + 1);
        } else {
            map.computeIfPresent(c, (k, v) -> v - 1);
        }
    }

    public static void main(String[] args) {
        String s = "ADOBECODEBANC";
        String t = "ABC";

        MinWindow2 minWindow2 = new MinWindow2();
        String s1 = minWindow2.minWindow(s, t);
        System.out.println(s1);
    }
}
